<template>
	<div class="form-area">
		<el-form ref="addForm" :model="addForm" :rules="rules" label-width="140px" style="width: 80%; height:auto;">
			<!-- 商品信息 -->
			<div class="form-title">
				<h3>商品信息</h3>
			</div>

			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="商品名称" prop="productName">
						<el-input v-model="addForm.productName" placeholder="请输入商品名称" :readonly="isDetails"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="商品编码" prop="productCode">
						<el-input v-model="addForm.productCode" placeholder="请输入商品编码" :readonly="productCodeReadonly || isDetails"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="商品分类" prop="thirdLevelId">
						<el-input :value="productDetails.firstLevelName+'-'+productDetails.secondLevelName+'-'+productDetails.thirdLevelName" :readonly="isDetails" v-if="isDetails"></el-input>
						<el-cascader v-model="addForm.thirdLevelId" :options="categoryTree" :props="{ value: 'id', label: 'categoryName' }" @change="handleChangeCategory" placeholder="请选择商品分类" style="width: 100%;" v-if="!isDetails"></el-cascader>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="商品品牌" prop="brandId">
						<el-input :value="addForm.brandName" :readonly="isDetails" v-if="isDetails"></el-input>
						<el-cascader v-model="addForm.brandId" :options="brandTree" :props="{ value: 'id', label: 'brandName' }" @change="handleChangeBrand" placeholder="请选择商品品牌" style="width: 100%;" v-if="!isDetails"></el-cascader>
					</el-form-item>
				</el-col>

				<el-col :span="12">
					<el-form-item label="品牌LOGO" prop="brandLogo">
						<el-image :src="addForm.brandLogo" style="width: 10%; height:10%;">
							<div slot="error" class="image-placeholder">
								<i class="el-icon-picture-outline"></i>
							</div>
						</el-image>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="所属厂家" prop="brandFirm">
						<el-input v-model="addForm.brandFirm" placeholder="请输入所属厂家" readonly></el-input>
					</el-form-item>
				</el-col>

				<el-col :span="12">
					<el-form-item label="状态" prop="status">
						<el-radio-group v-model="addForm.status">
							<el-radio label="0" border :disabled="isUpdate || isDetails">下架</el-radio>
							<el-radio label="1" border :disabled="isUpdate || isDetails">上架</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="商品单位" prop="productUnit">
						<div v-if="addForm.unitList.length > 0">
							<span v-for="(item, index) of addForm.unitList" :key="index">
								{{item.unitName}}<template v-if="item.isSkuPack">（库存单位）</template>，转换系数：{{item.ratio}}；&nbsp;&nbsp;
							</span>
						</div>
						<el-button type="primary" plain @click="setUnit" v-if="!isDetails">添加单位</el-button>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="商品主图" prop="mainImage">
						<el-card style="height: 180px;width: 180px;" shadow="hover">
							<el-image :src="localMainImage">
								<div slot="error" class="image-slot"><i>请上传图片</i></div>
							</el-image>
						</el-card>
						
						<el-upload
							ref="uploadMainImage"
							:accept="'image/*'"
							list-type="picture"
							:show-file-list="false"
							:auto-upload="false"
							:headers="headerParams"
							:action="getUploadUrl()"
							:on-exceed="handleExceedMainImage"
							:on-change="imgPreviewMainImage"
							:on-success="handleSuccessMainImage"
							:on-error="handleErrorMainImage"
							v-if="!isDetails"
						>
							<div style="margin-top: 12px;">
								<el-button slot="trigger" size="small" type="primary" @click="clickMainImageSelect">选取图片</el-button>
								<el-button style="margin-left: 10px;" size="small" type="success" @click.stop.prevent="submitUploadMainImage">上传到服务器</el-button>
								<br />
								<el-button id="myImage" type="primary" icon="el-icon-folder-opened" @click.stop.prevent="showMyImageMain()">收藏夹</el-button>
								<el-button class="addMyImage" :class="{ addNotMyImage: mainImageCanCollecting }" type="primary" icon="el-icon-circle-plus-outline" :disabled="mainImageCanCollecting" @click.stop.prevent="addImageMain">添加收藏</el-button>
								<div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件</div>
							</div>
						</el-upload>
					</el-form-item>
				</el-col>

				<el-col :span="12">
					<el-form-item label="商品缩略图" prop="thumbImage">
						<el-card style=" width: 180px;height: 180px;" shadow="hover">
							<el-image :src="localThumbImage">
								<div slot="error" class="image-slot">
									<i>请上传图片</i>
								</div>
							</el-image>
						</el-card>

						<el-upload
							ref="uploadThumbImage"
							:accept="'image/*'"
							list-type="picture"
							:show-file-list="false"
							:auto-upload="false"
							:headers="headerParams"
							:action="getUploadUrl()"
							:on-exceed="handleExceedThumbImage"
							:on-change="imgPreviewThumbImage"
							:on-success="handleSuccessThumbImage"
							:on-error="handleErrorThumbImage"
							v-if="!isDetails"
						>
							<div style="margin-top: 12px;">
								<el-button slot="trigger" size="small" type="primary" @click="clickThumImageSelect">选取图片</el-button>
								<el-button style="margin-left: 10px;" size="small" type="success" @click.stop.prevent="submitUploadThumbImage">上传到服务器</el-button>
								<br />
								<el-button id="myImage" type="primary" icon="el-icon-folder-opened" @click.stop.prevent="showMyImageThumb()">收藏夹</el-button>
								<el-button class="addMyImage" :class="{ addNotMyImage: thumbImageCanCollecting }" type="primary" icon="el-icon-circle-plus-outline" :disabled="thumbImageCanCollecting" @click.stop.prevent="addImageThumb">添加收藏</el-button>
								<div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件</div>
							</div>
						</el-upload>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="商品轮播图" prop="carouselImageList">
						<div style="display: flex;" v-if="isDetails">
							<el-card shadow="hover" v-for="(item, index) of fileList" :key="index" style="height: 180px;width: 180px;">
								<el-image :src="item.url">
									<div slot="error" class="image-slot"><i>请上传图片</i></div>
								</el-image>
							</el-card>
						</div>
						
						<template v-if="!isDetails">
							<el-upload
								ref="upload"
								list-type="picture-card"
								:file-list="fileList"
								:limit="9"
								:accept="'image/*'"
								action=""
								:http-request="(file) => getQiniuToken(file, 3)"
								:before-upload="imgPreviewCarouselImage"
								:before-remove="handleRemove"
							>
								<i class="el-icon-plus avatar-uploader-icon" slot="default" ></i>
							</el-upload>
						</template>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="商品备注" prop="productRemark">
						<el-input type="textarea" v-model="addForm.productRemark" :readonly="isDetails"></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item label="商品描述" prop="productDesc">
						<div v-html="addForm.productDesc" v-if="isDetails"></div>
						<d2-ueditor v-model="addForm.productDesc" v-if="!isDetails"></d2-ueditor>
					</el-form-item>
				</el-col>
			</el-row>

			<!-- 保存 -->
			<el-row :gutter="20">
				<el-col :span="24">
					<el-form-item>
						<div class="form-submit">
							<el-button class="form-submit-btn" :disabled="loading" type="primary" @click="onSubmit('addForm')" v-if="!isDetails">保存</el-button>
							<el-button class="form-cancle-btn" :disabled="loading" @click="closePage" v-if="isDetails">返回</el-button>
							<el-button class="form-cancle-btn" :disabled="loading" @click="next">下一步</el-button>
						</div>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>

		<chooseImagePage
			:choiseMainComponent="choiseMainComponent"
			@close-choose-image-page="closeChooseMainImagePage"
			@choosed-image="choosedMainImage"
		></chooseImagePage>

		<chooseImagePage
			:choiseThumbComponent="choiseThumbComponent"
			@close-choose-image-page="closeChooseThumbImagePage"
			@choosed-image="choosedThumbImage"
		></chooseImagePage>

		<el-dialog title="商品单位" width="40%" :visible.sync="showUnitDialog">
			<div class="form-title" style="padding-bottom: 10px;">
				<el-button type="warning" size="medium" @click="addUnitList">增加单位</el-button>
			</div>
			
			<div class="form-table" style="padding: 0;">
				<el-table :data="unitList" border style="width: 100%">
					<el-table-column label="单位名称">
						<template slot-scope="scope">
							<el-input v-model="scope.row.unitName" placeholder="单位名称"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="库存单位" width="90">
						<template slot-scope="scope">
							<el-checkbox v-model="scope.row.isSkuPack" @change="setSkuPack(scope.$index)"></el-checkbox>
						</template>
					</el-table-column>
					<el-table-column label="转换系数" width="180">
						<template slot-scope="scope">
							<el-input v-model="scope.row.ratio" placeholder="转换系数"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="76">
						<template slot-scope="scope">
							<el-button icon="el-icon-delete" circle @click="delectUnit(scope.$index)"></el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<div class="dialog-footer" slot="footer">
				<el-button type="primary" @click="saveUnit">保存</el-button>
				<el-button @click="showUnitDialog = false">取消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import util from '@/libs/util'
	import * as qiniu from 'qiniu-js'
	import { ossDomain } from '@api/sys.common'
	import { uploadImageUrl, getQiniuToken } from '@api/common/common'
	import { saveImage } from '@api/sysImageFavorite/sysImageFavorite'
	import { save } from '@api/product/product'
	import { findBrandTree } from '@api/product/productBrand'
	import { findCategoryTree } from '@api/product/productCategory'
	import chooseImagePage from '../../../system/sysImageFavorite/chooseImage'
	export default {
		components: {
			chooseImagePage
		},
		props: {
			isDetails: {
				type: Boolean,
				default: false
			},
			isUpdate: {
				type: Boolean,
				default: false
			},
			productDetails: Object,
			productUnitList: Array
		},
		data() {
			let validateProductUnit = (rule, value, callback) => {
				if (this.addForm.unitList.length == 0) {
					callback(new Error('请添加商品单位！'))
				} else {
					callback()
				}
			}
			return {
				brandTree: [],
				categoryTree: [],
				productCodeReadonly: false,

				addForm: { // 商品信息
					productName: '',
					productCode: '',
					brandId: '',
					brandName: '',
					brandLogo: '',
					brandFirm: '',
					status: '0',
					firstLevelId: '',
					secondLevelId: '',
					thirdLevelId: '',
					productDesc: '',
					productRemark: '',
					mainImage: '',
					thumbImage: '',
					carouselImageList: [],
					unitList: []
				},

				rules: { // 表单验证规则
					productName: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}, {
						min: 1,
						max: 60,
						message: '长度在 1 到 60 个字符',
						trigger: 'blur'
					}],
					productCode: [{
						required: true,
						message: '请输入商品编码',
						trigger: 'blur'
					}, {
						min: 1,
						max: 15,
						message: '长度在 1 到 15 个字符',
						trigger: 'blur'
					}],
					brandId: [{
						required: true,
						message: '请选择商品品牌',
						trigger: 'blur'
					}],
					brandFirm: [{
						required: true,
						message: '请输入所属厂家',
						trigger: 'blur'
					}],
					productUnit: [{
						required: true,
						validator: validateProductUnit
					}],
					thirdLevelId: [{
						required: true,
						message: '请选择商品三级分类',
						trigger: 'blur'
					}],
					productRemark: [{
						required: true,
						message: '请输入商品备注',
						trigger: 'blur'
					}, {
						min: 1,
						max: 60,
						message: '长度在 1 到 60 个字符',
						trigger: 'blur'
					}],
					productDesc: [{
						required: true,
						message: '请输入商品描述',
						trigger: 'blur'
					}],
					mainImage: [{
						required: true,
						message: '请上传商品主图',
						trigger: 'blur'
					}],
					thumbImage: [{
						required: true,
						message: '请上传商品缩略图',
						trigger: 'blur'
					}],
					carouselImageList: [{
						required: true,
						message: '请上传商品轮播图',
						trigger: 'change'
					}]
				},

				unitList: [], // 商品单位列表
				showUnitDialog: false,

				loading: false,
				gotoNext: false,

				param: {},

				// 图片上传插件
				fileList: [], // 轮播图
				temporaryList: [],
				localMainImage: '', // 主图
				localThumbImage: '', // 缩略图图
				choiseMainComponent: false,
				choiseThumbComponent: false,
				mainImageCanCollecting: true,
				thumbImageCanCollecting: true,
				headerParams: { // 上传图片的请求头
					client_id: '',
					democracy: ''
				},

				mainImageFile: '', //主图选取文件
				thumbImageFile: '', //缩略图选取文件

				//七牛云参数
				file: '',
				qiniuKey: '',
				qiniuToken: '',
				qiniuPutExtra: {},
				qiniuConfig: {
					useCdnDomain: true,
					retryCount: 6,
				},
			}
		},
		watch: {
			productDetails(val) {
				this.$set(this.addForm, 'productId', val.productId)

				// 编辑-商品编码改成只读
				if (val.productId != '' && val.productId != undefined) {
					this.productCodeReadonly = true
				}

				this.addForm.productName = val.productName
				this.addForm.productCode = val.productCode
				this.addForm.brandId = val.brandId
				this.addForm.brandName = val.brandName
				this.addForm.brandLogo = val.brandLogo
				this.addForm.brandFirm = val.brandFirm
				this.addForm.status = val.status + ""
				this.addForm.firstLevelId = val.firstLevelId
				this.addForm.secondLevelId = val.secondLevelId
				this.addForm.thirdLevelId = val.thirdLevelId
				this.addForm.productRemark = val.productRemark
				this.addForm.productDesc = val.productDesc
				this.addForm.mainImage = val.mainImage
				this.addForm.thumbImage = val.thumbImage

				this.localMainImage = val.mainImage
				this.localThumbImage = val.thumbImage

				val.carouselImageList.forEach(item => {
					this.addForm.carouselImageList.push({
						carouselImage: item.carouselImage
					})
				})
				// 轮播图列表
				this.addForm.carouselImageList.forEach(item => {
					this.fileList.push({
						url: item.carouselImage,
						name: item.carouselImage
					})
				})
			},
			productUnitList(val) {
				this.addForm.unitList = val
				let list = val
				list.forEach(item => {
					this.unitList.push({
						productId: item.productId,
						id: item.id,
						unitName: item.unitName,
						ratio: item.ratio,
						isSkuPack: item.isSkuPack == 1
					})
				})
			}
		},
		methods: {
			// 商品信息start
			getBrandList() { // 品牌
				findBrandTree({ parentId: 0 })
					.then(res => {
						// 调用递归方法，去除级联数据后将数据赋值给级联选择器
						this.brandTree = this.getTreeData(res.data);
					})
					.catch(err => {
						console.log('err', err)
					})
			},
			getCategoryList() { // 分类
				findCategoryTree({ parentId: 0 })
					.then(res => {
						// 调用递归方法，去除级联数据后将数据赋值给级联选择器
						this.categoryTree = this.getTreeData(res.data);
					})
					.catch(err => {
						console.log('err', err)
					})
			},
			getTreeData(data) { // 分类数据整理
				for (var i = 0; i < data.length; i++) {
					if (data[i].children == 'null' || data[i].children.length < 1) {
						// children若为空数组，则将children设为undefined
						data[i].children = undefined;
					} else {
						// children若不为空数组，则继续 递归调用 本方法
						this.getTreeData(data[i].children);
					}
				}
				return data
			},

			handleChangeBrand(value) { // 选择品牌
				this.addForm.brandId = value[value.length - 1]
				for (var brand of this.brandTree) {
					if (brand.id == this.addForm.brandId) {
						this.addForm.brandName = brand.brandName;
						this.addForm.brandLogo = brand.brandLogo;
						this.addForm.brandFirm = brand.brandFirm;
					}
				}
			},
			handleChangeCategory(value) { // 选择分类
				this.addForm.firstLevelId = '';
				this.addForm.secondLevelId = '';
				this.addForm.thirdLevelId = '';

				if (value.length > 0) {
					this.addForm.firstLevelId = value[0];
				}
				if (value.length > 1) {
					this.addForm.secondLevelId = value[1];
				}
				if (value.length > 2) {
					this.addForm.thirdLevelId = value[2];
				}
			},

			// 上传轮播图（已废弃）
			handlePictureList(res) { // 上传成功回调
				this.addForm.carouselImageList.push({
					carouselImage: res
				})
			},
			handleRemove(file, fileList) { // 删除图片
				let filePath = file.response
				if (filePath) {
					let i = this.addForm.carouselImageList.findIndex(x => x.carouselImage == filePath.message)
					this.addForm.carouselImageList.splice(i, 1); // 从列表中删除对应图片
				} else {
					let i = this.addForm.carouselImageList.findIndex(x => ossDomain + x.carouselImage == file.url)
					this.addForm.carouselImageList.splice(i, 1); // 从列表中删除对应图片
				}
			},
			imgPreviewCarouselImage(file, fileList) {
				let size = file.size;
				if(size > 1024*1024*2) {
					this.$message.error('图片大小不能超过2M！');
					return false;
				}
			},
			
			// 上传图片（已废弃）
			getUploadUrl() {
				return uploadImageUrl() + '?type=1';
			},
			imgPreviewMainImage(file, fileList) {
				let size = file.size;
				if(size > 1024*1024*2) {
					this.$message.error('图片大小不能超过2M！');
					fileList.splice(0);
					return;
				}
				
				if(fileList.length > 1) {
					fileList.splice(0, 1);
				}
				let fileName = file.name;
				let regex = /(.jpg|.jpeg|.png)$/;
				if (regex.test(fileName.toLowerCase())) {
					this.localMainImage = URL.createObjectURL(file.raw);
					// console.log("localMainImage",this.localMainImage);
					// console.log("(imgPreviewMainImage)this.mainImageCanCollecting="+this.mainImageCanCollecting)
				} else {
					this.$message.error('请选择图片文件');
					fileList.splice(0); // 强行清空记录
				}
				this.mainImageFile = file;
			},
			handleSuccessMainImage(response, file, fileList) {
				console.log('response:', response)
				if (response.code == '000000') {
					this.$message.success('上传图片成功')
					this.addForm.mainImage = response.data.url;
					// console.log("mainImage",this.addForm.mainImage);
					this.mainImageCanCollecting = false
					// console.log("(handleSuccessMainImage)this.mainImageCanCollecting="+this.mainImageCanCollecting)
				} else {
					this.$message.error('上传图片失败:' + response.message)
				}
				fileList.splice(0)
			},
			handleErrorMainImage(err, file, fileList) {
				this.$message.error('上传失败,请重新上传图片!' + err)
				fileList.splice(0)
			},
			handleExceedMainImage(files, fileList) {
				this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
			},
			submitUploadMainImage() { //上传主图
				// this.$refs.uploadMainImage.submit(); //原上传方法
				this.getQiniuToken(this.mainImageFile, 1); //七牛云上传
			},
			imgPreviewThumbImage(file, fileList) {
				let size = file.size;
				if(size > 1024*1024*2) {
					this.$message.error('图片大小不能超过2M！');
					fileList.splice(0);
					return;
				}
				
				if(fileList.length > 1) {
					fileList.splice(0, 1);
				}
				let fileName = file.name;
				let regex = /(.jpg|.jpeg|.png)$/;
				if (regex.test(fileName.toLowerCase())) {
					this.localThumbImage = URL.createObjectURL(file.raw);
					// console.log("localThumbImage",this.localThumbImage);
					// console.log("(imgPreviewThumbImage)thumbImageCanCollecting="+thumbImageCanCollecting);
				} else {
					this.$message.error('请选择图片文件');
					fileList.splice(0); // 强行清空记录
				}
				this.thumbImageFile = file;
			},
			handleSuccessThumbImage(response, file, fileList) {
				// console.log("response:", response);
				if (response.code == '000000') {
					this.$message.success('上传图片成功')
					this.addForm.thumbImage = response.data.url
					// console.log("thumbImage",this.addForm.thumbImage);
					this.thumbImageCanCollecting = false
					// console.log("(handleSuccessThumbImage)thumbImageCanCollecting="+thumbImageCanCollecting);
				} else {
					this.$message.error('上传图片失败:' + response.message)
				}
				fileList.splice(0)
			},
			handleErrorThumbImage(err, file, fileList) {
				this.$message.error('上传失败,请重新上传图片!' + err)
				fileList.splice(0)
			},
			handleExceedThumbImage(files, fileList) {
				this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
			},
			submitUploadThumbImage() { //上传缩略图
				// this.$refs.uploadThumbImage.submit(); //原上传方法
				this.getQiniuToken(this.thumbImageFile, 2); //七牛云上传
			},

			//七牛云上传
			getQiniuToken(file, type) { //获取七牛云token
				console.log(file)
				let name = '';
				if(type == 3) {
					name = file.file.name.split('.');
				} else {
					name = file.name.split('.');
				}
				let subffixName = '.' + name[name.length - 1];
				
				getQiniuToken({
						subffixName: subffixName
					})
					.then(res => {
						this.qiniuToken = res.data.token;
						this.qiniuKey = res.data.key;
						this.uploadFile(file, type);
					})
			},
			uploadFile(file, type) { //七牛云上传
				//qiniu.upload(file, key, token, putExtra, config)
				let fileItem = '';
				if(type == 3) {
					fileItem = file.file;
				} else {
					fileItem = file.raw;
				}
				const observable = qiniu.upload(
					fileItem,
					this.qiniuKey,
					this.qiniuToken,
					this.qiniuPutExtra,
					this.qiniuConfig
				)

				// 上传开始
				observable.subscribe({
					next: res => {
						console.log(res)
					},
					error: err => {
						console.log(err)
						if (type == 1) {
							this.handleErrorMainImage(err, file)
						} else if(type ==2) {
							this.handleErrorThumbImage(err, file)
						}
					},
					complete: res => {
						console.log(res)
						if (type == 1) {
							this.$message.success('上传图片成功');
							this.addForm.mainImage = process.env.VUE_APP_OSS_DOMAIN + res.key;
							this.mainImageCanCollecting = false;
						} else if (type == 2) {
							this.$message.success('上传图片成功');
							this.addForm.thumbImage = process.env.VUE_APP_OSS_DOMAIN + res.key;
							this.thumbImageCanCollecting = false;
						} else {
							this.$message.success('上传图片成功');
							this.handlePictureList(process.env.VUE_APP_OSS_DOMAIN + res.key)
						}
					},
				});
			},
			
			addImageMain() { // 主图-添加到收藏夹
				this.$prompt('请输入图片描述', '添加图片到收藏夹', {
						confirmButtonText: '确定',
						cancelButtonText: '放弃收藏'
					})
					.then(({ value }) => {
						saveImage({
								imageUrl: this.addForm.mainImage,
								remark: value
							})
							.then(res => {
								this.$message({
									message: '收藏成功',
									type: 'success'
								})
								this.mainImageCanCollecting = true
								this.loading = false
							})
							.catch(err => {
								console.log('err', err)
								this.loading = false
							})
					})
					.catch(() => {})
			},
			addImageThumb() { // 缩略图-添加到收藏夹
				this.$prompt('请输入图片描述', '添加图片到收藏夹', {
						confirmButtonText: '确定',
						cancelButtonText: '放弃收藏'
					})
					.then(({
						value
					}) => {
						saveImage({
								imageUrl: this.addForm.thumbImage,
								descript: value
							})
							.then(res => {
								this.$message({
									message: '收藏成功',
									type: 'success'
								})
								this.thumbImageCanCollecting = true
								this.loading = false
							})
							.catch(err => {
								console.log('err', err)
								this.loading = false
							})
					})
					.catch(() => {})
			},
			showMyImageMain() {
				this.choiseMainComponent = !this.choiseMainComponent;
			},
			showMyImageThumb() {
				this.choiseThumbComponent = !this.choiseThumbComponent;
			},
			closeChooseMainImagePage(val) {
				this.choiseMainComponent = val;
			},
			closeChooseThumbImagePage(val) {
				this.choiseThumbComponent = val;
			},
			choosedMainImage(val) {
				this.addForm.mainImage = val.imageUrlSource;
				this.localMainImage = val.imageUrl;
				this.mainImageCanCollecting = true;
			},
			choosedThumbImage(val) {
				this.addForm.thumbImage = val.imageUrlSource;
				this.localThumbImage = val.imageUrl;
				this.thumbImageCanCollecting = true;
			},
			clickMainImageSelect() {
				this.mainImageCanCollecting = true;
			},
			clickThumImageSelect() {
				this.thumbImageCanCollecting = true;
			},

			// 设置单位
			setUnit() { // 打开设置单位弹窗
				if (this.unitList.length == 0) {
					this.unitList.push({
						unitName: '',
						ratio: '',
						isSkuPack: true
					})
				}
				this.showUnitDialog = true;
			},
			addUnitList() { // 单位列表增加新的一行
				this.unitList.push({
					unitName: '',
					ratio: '',
					isSkuPack: false
				})
				if (this.addForm.productId) {
					this.unitList.forEach(item => {
						this.$set(item, 'productId', this.addForm.productId);
					})
				}
			},
			setSkuPack(index) { // 设置单位默认sku包装
				this.unitList.forEach((item, itemIndex) => {
					if (itemIndex == index) {
						item.isSkuPack = true;
					} else {
						item.isSkuPack = false;
					}
				})
			},
			delectUnit(index) { // 单位列表删除一行
				if (this.unitList.length == 1) {
					this.$message.warning('只剩下一个单位，不能删除了！');
					return;
				}
				this.unitList.splice(index, 1);
			},

			saveUnit() { // 保存商品单位设置
				let isSkuPack = false

				for (let i in this.unitList) {
					if (!this.unitList[i].unitName) {
						this.$message.warning('单位名称不能为空！');
						return;
					}
					if (!this.unitList[i].ratio) {
						this.$message.warning('转换系数不能为空！');
						return;
					}
					if (!/^([1-9][0-9]*)$/.test(this.unitList[i].ratio)) {
						this.$message.warning('转换系数必须为正整数！');
						return;
					}
					if (this.unitList[i].isSkuPack) {
						isSkuPack = true;
					}
				}
				if (!isSkuPack) {
					this.$message.warning('请选择一个单位作为默认的库存单位！');
					return;
				}

				// 整理数据
				let list = this.objDeepCopy(this.unitList)
				list.forEach(item => {
					item.isSkuPack = item.isSkuPack ? 1 : 0;
				})
				this.addForm.unitList = list;

				this.$message.success('商品单位设置成功！');
				this.showUnitDialog = false;
			},

			// 提交
			onSubmit(formName) {
				this.$refs[formName].validate(valid => {
					if (valid) {
						this.loading = true

						// 提交表单
						save(this.addForm)
							.then(res => {
								sessionStorage.setItem('productId', res.data.id);
								this.$message.success('保存成功');

								if (this.gotoNext) {
									this.$emit('next', 1);
									this.gotoNext = false;
								} else {
									this.$emit('close');
								}
								this.loading = false;
							})
							.catch(() => {
								this.loading = false;
								this.gotoNext = false;
							})
					} else {
						this.loading = false;
						this.gotoNext = false;
					}
				})
			},
			// 下一步
			next() {
				if (this.isDetails) {
					this.$emit('next', 1);
				} else {
					this.gotoNext = true;
					this.onSubmit('addForm');
				}
			},
			// 返回列表
			closePage() {
				this.$emit('close');
			},

			objDeepCopy(source) { // 深拷贝数组or对象
				let sourceCopy = source instanceof Array ? [] : {};
				for (let item in source) {
					sourceCopy[item] = typeof source[item] === 'object' ? this.objDeepCopy(source[item]) : source[item];
				}
				return sourceCopy;
			}
		},
		mounted() {
			this.getBrandList();
			this.getCategoryList();

			// 上传图片插件的请求头
			let getId = util.cookies.get('client');
			let client_id;
			let getId2_reverse = getId.substring(0, 6);
			let getId2 = getId2_reverse.split('').reverse().join(''); // 后6位
			let getId1 = getId.substring(6, 13); // 前7位
			client_id = 'client' + getId1 + getId2;

			let democracy = util.cookies.get('democracy');

			this.headerParams.clientId = client_id;
			this.headerParams.democracy = democracy;
		}
	}
</script>

<style scoped>
	.step {
		width: 80%;
		padding: 20px 0 40px 0;
	}

	.step-title {
		cursor: pointer;
	}

	::v-deep .image-placeholder {
		width: 50px;
		height: 50px;
		align-items: center;
		justify-content: center;
		background-color: #eee;
		display: flex;
	}

	::v-deep .edui-editor-iframeholder.edui-default {
		height: 300px !important;
	}
	
	::v-deep img {
		max-width: 100%!important;
	}
	
	#myImage {
		background-color: #6b116b;
		width: 80px;
		height: 32px;
		padding-top: 8px;
		padding-left: 8px;
		border-color: white;
	}

	.addMyImage {
		background-color: #b24cff;
		width: 104px;
		height: 32px;
		padding-top: 8px;
		padding-left: 12px;
		border: 0px solid white;
	}

	.addMyImage:hover {
		background-color: #b24cff;
	}

	.addNotMyImage {
		background-color: #ccc;
	}

	.addNotMyImage:hover {
		background-color: #ccc;
	}
</style>